package com.qyer.commons.report;

import com.qyer.commons.logger.ContentShowLogger;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * User: Z J Wu Date: 2016/04/11 Time: 17:34 Package: com.qyer.commons.report
 */
public class GenericReporter<T extends ReportItem> implements Runnable {

  private static final Logger LOGGER = LoggerFactory.getLogger(GenericReporter.class);

  private ReporterQueue<T> reporterQueue;

  private ContentShowLogger contentShowLogger;

  public GenericReporter(ReporterQueue<T> reporterQueue, ContentShowLogger contentShowLogger) {
    this.reporterQueue = reporterQueue;
    this.contentShowLogger = contentShowLogger;
  }

  @Override public void run() {
    T t;
    try {
      while (true) {
        t = reporterQueue.takeFromQueue();
        if (t == null) {
          continue;
        }
        if (t.isPill()) {
          break;
        }
        try {
          contentShowLogger.logContent(t);
        } catch (Exception e) {
          LOGGER.warn("Cannot send report({})", e);
        }
      }
    } catch (InterruptedException e) {
      LOGGER.warn("Reporter is interrupted", e);
    }
    LOGGER.info("Reporter is stopped.");
  }
}
